package org.qufenqi.api.controller.front;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import org.qufenqi.api.common.CommonResponse;
import org.qufenqi.api.entity.Addmoney;
import org.qufenqi.api.mapper.AddmoneyMapper;
import org.qufenqi.api.service.AliPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/Alipay/")
public class AliPayController {

    @Autowired
    private AliPayService aliPayService;

    @Autowired
    private AddmoneyMapper addmoneyMapper;

    //支付调用
    @PostMapping("alipaySum")
    @ResponseBody
    public String payForOrder(@RequestBody String info){


        JSONObject jsonObject = JSON.parseObject(info);
        double money = jsonObject.getDoubleValue("money");
        String username = jsonObject.getString("username");
        int min = 100000000;
        int max = 999999999;
        int x = (int)(Math.random()*(max-min)+min);
        System.out.println("x = "+x);
        String orderid = String.valueOf(x);
        System.out.println("orderid = " + orderid);
        System.out.println("用户是:" + username + " !!!!!!!!!!!!!!!!!!!!!!");
        System.out.println("钱的数量:" + money + " !!!!!!!!!!!!!!!!!");


        addmoneyMapper.deleteById(1);
        Addmoney addmoney = new Addmoney();
        addmoney.setId(1);
        addmoney.setUsername(username);
        addmoney.setUsermoney(money);
        addmoneyMapper.insert(addmoney);


        return aliPayService.payForOrder(orderid,money);
    }

    //异步回调
    @RequestMapping("notifyUrl")
    @ResponseBody
    public void notifyUrl(HttpServletResponse response, HttpServletRequest request) throws Exception{
        System.out.println("进入！");
        aliPayService.notifyUrl(response,request);
    }

    //同步回调
    @GetMapping("returnUrl")
    @ResponseBody
    public String returnUrl(HttpServletRequest request)throws IOException, AlipayApiException{
        return aliPayService.returnUrl(request);
    }

}
